<template>
  <div class="forget-pwd">
    <h1>找回密码</h1>
    <p>
      <span v-if="findWay">验证码将发送至手机{{ phoneNumber }}</span>
      <span v-else>验证码将发送至邮箱{{ email }}</span>
      <span
        class="changeMethod pointer"
        v-show="phone && email"
        @click="changeFindWay"
      >切换至{{ findWay ? '邮箱' : '手机' }}</span>
    </p>
    <el-form :model="form" :rules="rules" ref="ruleForm" status-icon>
      <el-form-item prop="slider" class="slider">
        <verify-slider
          v-model="form.slider"
          ref="slider"
          tips="请按住滑块，拖动到最后"
          @success="slideSuccess"
        ></verify-slider>
      </el-form-item>
      <el-form-item prop="identifyCode">
        <el-input placeholder="请输入验证码" v-model="form.identifyCode">
          <template slot="append">
            <el-button
              @click="getVCode"
              :disabled="identifyCodeMsg !== '获取验证码'"
            >{{ identifyCodeMsg }}</el-button>
          </template>
        </el-input>
        <div class="code-error" v-show="validateCodeError">验证码错误</div>
      </el-form-item>
      <el-form-item prop="password">
        <validate-pwd v-model="form.password" @setPassword="setPassword"></validate-pwd>
      </el-form-item>
      <el-form-item class="black-btn">
        <el-button @click="nextStep" :loading="loading" style="width: 400px;margin-top: 30px;">下一步</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { VerifySlider } from 'vue-verify-slider'
import ValidatePwd from '@/components/ValidatePwd'
export default {
  components: {
    VerifySlider,
    ValidatePwd
  },
  props: {
    userInfo: {
      type: Object,
      default: () => { }
    }
  },
  created() {
    this.phone = this.userInfo.telephone
    this.email = this.userInfo.email
    this.findWay = this.phone !== ''
  },
  data() {
    const validatePwd = (rule, value, callback) => {
      const reg = /(?!^[0-9]+$)(?!^[A-z]+$)(?!^[^A-z0-9]+$)^.{6,20}$/
      const reg2 = /^[^ ]+$/ // 判断密码是否包含空格
      if (!value) {
        return callback(new Error('密码不能为空'))
      } else if (!reg2.test(value)) {
        return callback(new Error('密码只能包含数字字母、标点符号（空格除外）'))
      } else if (value.length < 6 || value.length > 20) {
        return callback(new Error('密码长度需为6-20个字符'))
      } else if (!reg.test(value)) {
        return callback(new Error('密码强度不符合要求'))
      } else {
        return callback()
      }
    }
    const validateIdentifyCode = (rule, value, callback) => {
      if (!value) {
        this.validateCodeError = false
        return callback(new Error('验证码不能为空'))
      } else {
        return callback()
      }
    }
    const validateSlider = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请完成人机验证'))
      } else {
        return callback()
      }
    }
    return {
      phone: '',
      email: '',
      identifyCodeMsg: '获取验证码',
      validateCodeError: false,
      findWay: true,
      form: {
        password: '',
        slider: false
      },
      rules: {
        identifyCode: [{ validator: validateIdentifyCode, trigger: 'blur' }],
        password: [{ validator: validatePwd, trigger: 'blur' }],
        slider: [{ validator: validateSlider }]
      },
      loading: false
    }
  },
  computed: {
    phoneNumber() {
      const reg = /(\d{3})\d*(\d{4})/
      return this.phone.replace(reg, '$1****$2')
    }
  },
  methods: {
    setPassword(value) {
      this.form.password = value
    },
    // 切换找回密码方式
    changeFindWay() {
      this.findWay = !this.findWay
    },
    getVCode() {
      this.$refs.ruleForm.validateField('slider', () => {
        if (this.form.slider) {
          let time = 60
          let timer = setInterval(() => {
            this.identifyCodeMsg = time + 's 后重新获取'
            time--
            if (time < 0) {
              clearInterval(timer)
              this.identifyCodeMsg = '获取验证码'
            }
          }, 1000)
          const params = {
            uname: this.phone || this.email,
            pid: 210
          }
          this.$http.post(this.$service.getVCode, params).then(res => {
            const vCode = res.data.vCode
            if (this.findWay) {
              const info = {
                appId: 'cue_frontend',
                appToken: 'c890195cd04f0afffcc118812d83dca6',
                mobiles: [
                  this.phone
                ],
                msgContent: `尊敬的用户，本次操作验证码：${vCode}，10分钟内有效，请勿泄露。`,
                msgSignature: '【开域集团】'
              }
              this.$http.post(this.$service.sendPhoneVCode, info)
            } else {
              const params = {
                email: this.email,
                title: 'test',
                content: `尊敬的用户，本次操作验证码：${vCode}，10分钟内有效，请勿泄露。`,
                emailAddress: 'dvp_service@cue.group',
                emailAddressName: '开域集团',
                password: 'Abcd56789'
              }
              this.$http.post(this.$service.sendEmailCode, params)
            }
          })
        }
      })
    },
    slideSuccess() {
      this.form.slider = true
      this.$el.querySelector('.slider .el-form-item__error').style.display = 'none'
    },
    nextStep() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const params = {
            uname: this.phone || this.email,
            vCode: this.form.identifyCode,
            pid: 210
          }
          this.$http.post(this.$service.validateVCode, params).then(res => {
            this.validateCodeError = !res.data.validate
            if (res.data.validate) {
              this.loading = true
              const params = {
                uid: this.userInfo.uid,
                password: this.form.password
              }
              this.$http.post(this.$service.updateUserPwd, params).then(res => {
                if (res.message === '成功') {
                  this.$router.push({
                    path: '/validateSuccess',
                    query: {
                      state: 'modifyPwd'
                    }
                  })
                }
              }).finally(() => {
                this.loading = false
              })
            }
          })
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.forget-pwd {
  h1 {
    font-size: 30px;
    margin: 0;
  }
  p {
    font-size: 16px;
    color: #aaa;
    margin-bottom: 40px;
    .changeMethod {
      color: #546ffc;
    }
  }
  .code-error {
    font-size: 12px;
    color: #f56c6c;
    line-height: 1;
    position: absolute;
    top: 45px;
  }
  .drag {
    width: 100%;
    .drag_bg {
      width: 100% !important;
    }
  }
}
</style>
